#!/bin/sh
WorkDir=$(dirname $(pwd))
# 设置启动java文件名
JAR_NAME=%jar.name%\.jar

#第二个参数为进程实例ID
IID=None

#shell中获取本机ip地址 ---存在多个ip地址的话就默认取第一行ip
#IPAddress=`/sbin/ifconfig|sed -n '/inet addr/s/^[^:]*:\([0-9.]\{7,15\}\) .*/\1/p'|head -n 1`
#IPAddress=`/sbin/ifconfig -a |grep inet |grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d \"addr:\"`
IPAddress=%server.address%

#端口号
Port=%server.port%


#PID  代表是PID文件
PID=Pid

#使用说明，用来提示输入参数
usage() {
    echo "Usage: sh 执行脚本.sh [start|stop|restart|status]"
    exit 1
}

#检查程序是否在运行
is_exist(){
  pid=`ps ux|grep $JAR_NAME|grep $IID|grep -v grep|awk '{print $2}' `
  #如果不存在返回1，存在返回0
  if [ -z "${pid}" ]; then
   return 1
  else
    return 0
  fi
}

#启动方法
start(){
  is_exist
  if [ $? -eq "0" ]; then
    echo ">>> $JAR_NAME is already running PID=${pid} <<<"
  else
    nohup $JRE_HOME/bin/java -jar  -Dserver.port=$Port -Dinstance.id=$IID $WorkDir/$JAR_NAME >/dev/null 2>&1 &
    echo $! > $PID
    echo ">>> start $JAR_NAME successed PID=$! <<<"
   fi
  }



#停止方法
stop(){
  is_exist
  if [ $? -eq "0" ]; then
      pid=$(cat $PID)
      date '+%Y-%m-%d %H:%M:%S'
      echo ">>> $JAR_NAME begin kill $pid <<<"
      kill $pid
      echo ">>> process exiting please waiting<<<"

      iCnt=1
      while [ $iCnt -le 7 ]
      do
        let iCnt++
        sleep 2
        is_exist
        if [ $? -eq "0" ]; then
          echo ">>> $JAR_NAME process(${pid}) is not stopped 【WARN】<<<"
        else
          let iCnt+=15
          rm -rf $PID
          echo ">>> $JAR_NAME  is not running 【OK】<<<"
        fi
      done
      date '+%Y-%m-%d %H:%M:%S'
  else
      echo ">>> no such $JAR_NAME process<<<"
  fi
}

#输出运行状态
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo ">>> $JAR_NAME is running, pid = ${pid} <<<"
  else
    echo ">>> $JAR_NAME is not running <<<"
  fi
}

#重启
restart(){
  stop
  start
}


if [ $# -eq 2 ];
then
    IID=$2
elif [ $# -eq 0 ];
then
    usage
    exit
fi

  date '+%Y-%m-%d %H:%M:%S'
echo  $IPAddress "----------" $JAR_NAME  "----------" $WorkDir  "----------" $Port

#根据输入参数，选择执行对应方法，不输入则执行使用说明
case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  *)
    usage
    ;;
esac
exit 0
